package com.binguo.wxapi.schedule;

import com.alibaba.fastjson.JSONObject;
import com.binguo.common.enums.ZSDWXMessageTitle;
import com.binguo.common.sms.JavaSmsApi;
import com.binguo.common.sms.SMS;
import com.binguo.common.util.LoggerUtil;
import com.binguo.model.mapper.*;
import com.binguo.model.model.*;
import com.binguo.model.wxapi.form.ZSDWXGongZhongMessageForm;
import com.binguo.model.wxapi.vo.SMSOrderVO;
import com.binguo.service.NormalConfigService;
import com.binguo.service.ShopQucanguiSmsConfigService;
import com.binguo.wxapi.baidu.BaiduRecUtil;
import com.binguo.wxapi.form.aiyouwei.SaveOrderForm;
import com.binguo.wxapi.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Condition;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class WXScheduleService implements InitializingBean {

    private static Logger logger = LoggerFactory.getLogger(WXScheduleService.class);
    @Resource
    RedisLockService redisLockService;

    @Resource
    ShopOnlineMealMapper shopOnlineMealMapper;
    @Resource
    LogShopBaiduImgDelMapper logShopBaiduImgDelMapper;

    @Resource
    LogProductImgMapper logProductImgMapper;

    @Resource
    LogProductImgFromUserMapper logProductImgFromUserMapper;
    @Resource
    ShopBaiduUrlMapper shopBaiduUrlMapper;
    @Resource
    ProductMapper productMapper;

    @Autowired
    WXGongZHService wxGongZHService;

    @Autowired
    BaiduRecUtil baiduRecUtil;

    @Resource
    private NormalConfigService normalConfigService;

    private Set<Integer> productIdCheckedList;
    @Autowired
    private MessagePushService messagePushService;
    @Autowired
    private ShopQucanguiSmsConfigService shopQucanguiSmsConfigService;
    @Resource
    private AiyouweiTestService aiyouweiTestService;


    @Scheduled(cron="0 0/30 * * * ?") //
    public void delLogProductImg() throws Exception {
        LoggerUtil.console.info("====delLogProductImg===");
        String key = "delLogProductImg";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 200000, uuid);
        if (lock) {

            Condition condition = new Condition(ShopBaiduUrl.class);
            condition.or().andEqualTo("used", 1);
            List<ShopBaiduUrl> shopBaiduUrlList = shopBaiduUrlMapper.selectByCondition(condition);

            if (shopBaiduUrlList != null && shopBaiduUrlList.size() > 0) {
                Set<Integer> shopIdList = new HashSet<>();
                for (ShopBaiduUrl shopBaiduUrl : shopBaiduUrlList) {
                    shopIdList.add(shopBaiduUrl.getShopId());
                }


                if (shopIdList.size() > 0) {
                    for (Integer shopId : shopIdList) {
                        Condition productCondition = new Condition(Product.class);
                        productCondition.or().andEqualTo("shopid", shopId)
                        .andEqualTo("deleted", true);

                        List<Product> productList = productMapper.selectByCondition(productCondition);
                        if (productList != null && productList.size() > 0) {
                            List<Integer> productIdList = null;
                            for (Product product : productList) {
                                if (productIdCheckedList != null && productIdCheckedList.contains(product.getId())) {
                                    continue;
                                }

                                if (productIdList == null) {
                                    productIdList = new ArrayList<>();
                                }

                                productIdList.add(product.getId());
                            }

                            if (productIdList != null && productIdList.size() > 0) {
                                logger.info("productId list to be checked:{}", productIdList.size());
                            }else {
                                continue;
                            }
                            Condition logProductImgFromUserCondition = new Condition(LogProductImgFromUser.class);
                            logProductImgFromUserCondition.or()
                                    .andEqualTo("baiduDeleted", 0)
                                    .andEqualTo("shopId", shopId)
                                    .andIn("productId", productIdList)
                            ;

                            List<LogProductImgFromUser> logProductImgFromUserList =
                                    logProductImgFromUserMapper.selectByCondition(logProductImgFromUserCondition);

                            if (logProductImgFromUserList != null && logProductImgFromUserList.size() > 0) {
                                for (LogProductImgFromUser p : logProductImgFromUserList) {
                                    if(!baiduRecUtil.delImg(p.getContSign(), p.getShopId(), p.getBranchId())){
                                        LogShopBaiduImgDel temp = new LogShopBaiduImgDel();
                                        temp.setImgType(2);
                                        temp.setStatus(0);
                                        temp.setLogId(p.getId());

                                        logShopBaiduImgDelMapper.insertSelective(temp);

                                    }else {
                                        if (productIdCheckedList == null) {
                                            productIdCheckedList = new HashSet<>();
                                        }
                                        productIdCheckedList.add(p.getProductId());
                                    }
                                }
                            }
                        }

                    }
                }

            }

        }
    }



    @Scheduled(cron="0 0/10 * * * ?")
    public void delShopBaiduUrlImg() throws Exception {
        LoggerUtil.console.info("====delShopBaiduUrlImg===");
        String key = "delShopBaiduUrlImg";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 20000, uuid);
        if (lock) {
            Condition condition = new Condition(LogShopBaiduImgDel.class);
            condition.or().andEqualTo("status", 0);
            List<LogShopBaiduImgDel> imgDelList = logShopBaiduImgDelMapper.selectByCondition(condition);
            if (imgDelList != null && imgDelList.size() > 0) {
                for (LogShopBaiduImgDel logShopBaiduImgDel : imgDelList) {

                    if (logShopBaiduImgDel.getImgType() == null || logShopBaiduImgDel.getImgType().intValue() == 2) {
                        LogProductImgFromUser p = logProductImgFromUserMapper.selectByPrimaryKey(logShopBaiduImgDel.getLogId());
                        if (p != null) {
                            if(baiduRecUtil.delImg(p.getContSign(), p.getShopId(), p.getBranchId())){
                                LogShopBaiduImgDel temp = new LogShopBaiduImgDel();
                                temp.setId(logShopBaiduImgDel.getId());
                                temp.setStatus(1);

                                logShopBaiduImgDelMapper.updateByPrimaryKeySelective(temp);
                            }
                        }
                    }else {
                        LogProductImg p = logProductImgMapper.selectByPrimaryKey(logShopBaiduImgDel.getLogId());
                        if (p != null) {
                            if(baiduRecUtil.delImg(p.getContSign(), p.getShopId(), p.getBranchId())){
                                LogShopBaiduImgDel temp = new LogShopBaiduImgDel();
                                temp.setStatus(1);
                                temp.setId(logShopBaiduImgDel.getId());

                                logShopBaiduImgDelMapper.updateByPrimaryKeySelective(temp);
                            }
                        }
                    }

                }
            }
        }
    }




    @Scheduled(cron="0 0 3 * * ?") //每天10:00执行
    public void updateShopBreakfastMealConfig() throws Exception {
        String key = "updateShopBreakfastMealConfig";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {

            List<ShopOnlineMeal> shopOnlineMealList = shopOnlineMealMapper.selectAll();
            if (shopOnlineMealList != null && shopOnlineMealList.size() > 0) {
                for (ShopOnlineMeal shopOnlineMeal : shopOnlineMealList) {
                    if (shopOnlineMeal.getIsAutoConfig() == 1) {
                        shopOnlineMeal.setBreakfastStatus(1);
                        shopOnlineMeal.setLunchStatus(0);
                        shopOnlineMeal.setDinnerStatus(0);

                        shopOnlineMealMapper.updateByPrimaryKeySelective(shopOnlineMeal);
                    }
                }
            }
        }
    }

    @Scheduled(cron="0 59 9 * * ?") //每天10:00执行
    public void updateShopLunchMealConfig() throws Exception {
        String key = "updateShopLunchMealConfig";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {

            List<ShopOnlineMeal> shopOnlineMealList = shopOnlineMealMapper.selectAll();
            if (shopOnlineMealList != null && shopOnlineMealList.size() > 0) {
                for (ShopOnlineMeal shopOnlineMeal : shopOnlineMealList) {
                    if (shopOnlineMeal.getIsAutoConfig() == 1) {
                        shopOnlineMeal.setBreakfastStatus(0);
                        shopOnlineMeal.setLunchStatus(1);
                        shopOnlineMeal.setDinnerStatus(0);

                        shopOnlineMealMapper.updateByPrimaryKeySelective(shopOnlineMeal);
                    }
                }
            }
        }
    }

    @Scheduled(cron="0 0 15 * * ?") //每天10:00执行
    public void updateShopDinnerMealConfig() throws Exception {
        String key = "updateShopDinnerMealConfig";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {

            List<ShopOnlineMeal> shopOnlineMealList = shopOnlineMealMapper.selectAll();
            if (shopOnlineMealList != null && shopOnlineMealList.size() > 0) {
                for (ShopOnlineMeal shopOnlineMeal : shopOnlineMealList) {
                    if (shopOnlineMeal.getIsAutoConfig() == 1) {
                        shopOnlineMeal.setBreakfastStatus(0);
                        shopOnlineMeal.setLunchStatus(0);
                        shopOnlineMeal.setDinnerStatus(1);

                        shopOnlineMealMapper.updateByPrimaryKeySelective(shopOnlineMeal);
                    }
                }
            }
        }
    }

    @Scheduled(cron="0 0 * * * ?")//每个整点执行一次
    public void updateWxAccessToken(){
        String key = "updateWxAccessToken";

        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            logger.info("========================updateWxAccessToken");
            wxGongZHService.getWxToken();
        }
    }


    @Override
    public void afterPropertiesSet() throws Exception {
//        updateWxAccessToken();
    }

//    @Scheduled(cron="0 0 0/1 * * ?")//每个整点执行一次
    public void sendMessage()throws IOException {
        String key = "sendShopPushMsg";
        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            messagePushService.sendMessageByTime();
        }
    }

    /**
     * 查找出超时订单发送给用户和商户
     */
    @Scheduled(cron="0 */10 * * * ?")//每隔10分钟执行一次
    public void sengMealMessage() throws Exception{
        String key = "sendOrderInfoToCustomerAndShop";
        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            List<SMSOrderVO> smsOrderVOList =  shopQucanguiSmsConfigService.getAllCustomerInfo();
            Map<String ,String> map = new HashMap<>();
            for(SMSOrderVO smsOrderVO : smsOrderVOList){
                logger.info("发送浙师大相关信息!参数为:"+smsOrderVO.toString());
                sendZSDMessage(smsOrderVO);
                map.put(smsOrderVO.getBranchId().toString(), JSONObject.toJSONString(smsOrderVO));
            }
        }
    }

    /**
     * 定时查找出符合提醒条件的订单发送给用户
     */
    @Async
    @Scheduled(cron="0 */10 * * * ?")//每隔10分钟执行一次
    public void sendMealMessageBySetting()throws Exception{
        String key = "sendOrderInfoToCustomer";
        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLock(key, 10000, uuid);
        if (lock) {
            List<SMSOrderVO> smsOrderVOList =  shopQucanguiSmsConfigService.getCustomerInfoBySetting();

            for(SMSOrderVO smsOrderVO : smsOrderVOList){
                Integer hour = smsOrderVO.getMinute()/60;
                Integer mintus = smsOrderVO.getMinute()%60;
                String times = "";
                if(hour == 0){
                    times = mintus+"分钟";
                }else{
                    times = hour+"小时"+mintus+"分钟";
                }
                SaveOrderForm saveOrderForm = new SaveOrderForm();
                saveOrderForm.setCellNo(smsOrderVO.getCell());
                saveOrderForm.setPhone(smsOrderVO.getCustomerPhone());
                saveOrderForm.setMealCode(smsOrderVO.getMealCode());
                String strDateFormat = "yyyy-MM-dd HH:mm:ss";
                SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
                saveOrderForm.setShopPhone(normalConfigService.getConfigById(8).getValue());
                String time = sdf.format(smsOrderVO.getSaveTime());
                ZSDWXGongZhongMessageForm zsdwxGongZhongMessageForm = AiyouweiTestServiceImpl.getZSDWXGongZhongMessageForm(saveOrderForm,smsOrderVO.getSideBoardName(), ZSDWXMessageTitle.MEAL_AGAIN_TITLE.getTitle(),time,null);
                String host = getConfigUrl(1);
                if (null == smsOrderVO.getOpenId()){
                    boolean flag = aiyouweiTestService.sendWXGongZhoneMessage(smsOrderVO.getOpenId(),host,zsdwxGongZhongMessageForm);
                    if(!flag){
                        logger.info(new Date() + "定时发送失败！");
                    }else{
                        logger.info(new Date() + "定时发送成功！");
                    }
                }

                SMS sms  = JavaSmsApi.sendQuCanGuiDengDai(saveOrderForm.getPhone(),smsOrderVO.getMealCode(),times,smsOrderVO.getSideBoardName()+"取餐柜");
                if(sms.getCode()==0){
                    logger.info(new Date() + "发送给用户成功！");
                }else{
                    logger.info(new Date() + "发送给用户失败！");
                }
            }
        }
    }

    public void sendZSDMessage(SMSOrderVO smsOrderVO)throws Exception{
        Integer hour = smsOrderVO.getMinute()/60;
        Integer mintus = smsOrderVO.getMinute()%60;
        String times = "";
        if(hour == 0){
            times = mintus+"分钟";
        }else{
            times = hour+"小时"+mintus+"分钟";
        }
        SaveOrderForm saveOrderForm = new SaveOrderForm();
        saveOrderForm.setCellNo(smsOrderVO.getCell());
        saveOrderForm.setPhone(smsOrderVO.getCustomerPhone());
        saveOrderForm.setMealCode(smsOrderVO.getMealCode());
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        saveOrderForm.setShopPhone(normalConfigService.getConfigById(4).getValue());
        String time = sdf.format(smsOrderVO.getSaveTime());
        ZSDWXGongZhongMessageForm zsdwxGongZhongMessageForm = AiyouweiTestServiceImpl.getZSDWXGongZhongMessageForm(saveOrderForm,smsOrderVO.getSideBoardName(), ZSDWXMessageTitle.MEAL_OVERTIME_TITLE.getTitle(),time,null);
        String host = getConfigUrl(1);
        if (null == smsOrderVO.getOpenId()){
            boolean flag = aiyouweiTestService.sendWXGongZhoneMessage(smsOrderVO.getOpenId(),host,zsdwxGongZhongMessageForm);
            if(!flag){
                logger.info(new Date() + "定时发送失败！");
            }else{
                logger.info(new Date() + "定时发送成功！");
            }
        }

        SMS sms  = JavaSmsApi.sendQuCanGuiTimeout(smsOrderVO.getCustomerPhone(),smsOrderVO.getShopPhone(),smsOrderVO.getMealCode(),times,smsOrderVO.getSideBoardName()+"取餐柜");
        if(sms.getCode()==0){
            logger.info(new Date() + "定时发送失败！");
        }else{
            logger.info(new Date() + "定时发送成功！");
        }
        if(smsOrderVO.getShopId()==246 && smsOrderVO.getBranchId() == 274){
            sms = JavaSmsApi.sendQuCanGuiTimeoutShop(saveOrderForm.getShopPhone(),smsOrderVO.getCustomerPhone(),smsOrderVO.getMealCode(),times,smsOrderVO.getSideBoardName()+"取餐柜");
            if(sms.getCode()==0){
                logger.info(new Date() + "发送给商户成功！");
            }else{
                logger.info(new Date() + "发送给商户失败！");
            }
        }

    }

    public String getConfigUrl(Integer id){
        NormalConfig config = normalConfigService.getConfigById(id);
        return config.getValue();
    }


}
